<script setup>
import {computed, watch} from 'vue'
import {imageFileChoice, videoFileChoice} from '@/utils/file-choice'

//定义参数
const props = defineProps({
  modelValue: {},
  arrayLimit: {
    type: Number,
    default: 9
  },
  mediaType: {
    type: String,
    default: 'image',
    validator: (val) => ['image', 'video'].includes(val)
  }
})

//定义发射事件
const emit = defineEmits(['update:modelValue'])

//选择的文件名称
const getFileName = (file) => file?.filename !== undefined ? file.filename : file

//选择文件
const handleChoose = () => {
  const fileChoice = props.mediaType === 'image' ? imageFileChoice : videoFileChoice

  fileChoice.choose(props.arrayLimit).then((files) => {
    //如果不是数组则转换成数组
    const newValue = props.arrayLimit !== 1 ? [...props.modelValue, ...files] : files
    emit('update:modelValue', newValue)
  })
}

//删除文件
const handleDelete = (item) => {
  const newValue = props.arrayLimit !== 1 ? props.modelValue.filter(i => i !== item) : ''
  emit('update:modelValue', newValue)
}
</script>

<template>
  <div class="upload-files">
    <!-- 上传按钮 -->
    <div class="top">
      <el-button icon="Upload" text bg @click="handleChoose">选择文件</el-button>
    </div>

    <!-- 文件列表 -->
    <template v-for="item in Array.isArray(modelValue) ? modelValue : [modelValue]" v-if="modelValue" :key="item">
      <div class="upload-item">
        <!-- 文件预览 -->
        <view class="left">
          <el-icon>
            <Document/>
          </el-icon>
          <el-text class="file-name" truncated>{{ getFileName(item) }}</el-text>
        </view>

        <!-- 删除图片 -->
        <el-icon>
          <CloseBold class="delete-icon" @click="handleDelete(item)"/>
        </el-icon>
      </div>
    </template>
  </div>
</template>

<style lang="scss" scoped>
.upload-files {
  @include flex-box(false, true);
  gap: $spacing-4;
  width: 100%;

  .top {
    width: 200px;
  }

  .upload-item, .left, .right {
    @include flex-box;
    align-items: center;
    gap: $spacing-5;
  }

  .upload-item {
    justify-content: space-between;
    cursor: pointer;

    &:hover {
      background: $light-bg;

      .delete-icon {
        display: flex;
      }
    }

    .left {
      width: 85%;
    }

    .delete-icon {
      display: none;
      color: $red;
    }
  }
}
</style>
